package by.yakusekmaxim.bookgid.webapp.page.admin.image;

import javax.inject.Inject;

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.bean.validation.PropertyValidator;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.CompoundPropertyModel;

import by.yakusekmaxim.bookgid.datamodel.Image;
import by.yakusekmaxim.bookgid.services.ImageService;
import by.yakusekmaxim.bookgid.webapp.page.AdminLayout;
import by.yakusekmaxim.bookgid.webapp.page.admin.user.UserPage;

public class EditImagePage extends AdminLayout {

	@Inject
	private ImageService imageService;

	public EditImagePage(final Image image) {


		Form<Image> form = new Form<Image>("form",
				new CompoundPropertyModel<Image>(image));

		final Label tfId = new Label("id", image.getId());
		form.add(tfId);

		final TextField<String> tfName = new TextField<String>("name");
		tfName.add(new PropertyValidator<String>());
		form.add(tfName);

		Label imageLabel = new Label("imageLabel", "");
		if (image.getUrl() != null) {
			imageLabel.add(AttributeModifier.replace("src", image.getUrl()));
		} else {
			imageLabel
					.add(AttributeModifier.replace("style", "display: none;"));
		}
		imageLabel.setOutputMarkupId(true);
		form.add(imageLabel);

		final ImageUploadPanel uploadContainer = new ImageUploadPanel(
				"uploadContainer", imageLabel, image);
		uploadContainer.add(AttributeModifier
				.replace("style", "display: none;"));
		uploadContainer.setOutputMarkupId(true);
		add(uploadContainer);

		AjaxLink<Void> ajaxlink = new AjaxLink<Void>("updatedText") {
			@Override
			public void onClick(AjaxRequestTarget target) {
				uploadContainer.add(AttributeModifier.replace("style",
						"display: block;"));
				target.add(uploadContainer);
			}

		};

		form.add(ajaxlink);

		form.add(new SubmitLink("cancel") {
			@Override
			public void onSubmit() {
				super.onSubmit();

				ImagePage page = new ImagePage();
				setResponsePage(page);
			}

			@Override
			public void onError() {

				super.onError();
			}
		});

		form.add(new SubmitLink("save") {
			@Override
			public void onSubmit() {
				super.onSubmit();

				imageService.saveOrUpdate(image);

				UserPage page = new UserPage();

				// page.error("Custom error");
				page.info("Профиль ID: " + image.getId() + " сохранён!");
				// page.warn("Custom warn");

				setResponsePage(page);
			}

			@Override
			public void onError() {

				super.onError();
			}
		});
		add(form);

	}

	@Override
	protected WebMarkupContainer getTarget() {
		return targetImage;
	}

}
